package service

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	_ "go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"monitoring-api/models"
	"monitoring-api/serializer"
)

var (
	area []int
)

// GetUserAreaService 管理获取用户地区分布信息服务
type GetUserAreaService struct {
}

func (service *GetUserAreaService) Count() serializer.Response {
	//查询语句
	group := bson.D{
		{"$group", bson.D{
			{"_id", "$area"},
			{"count_total", bson.D{
				{"$sum", 1},
			}},
		}}}
	match := bson.D{
		{"$match", bson.D{{"webid", 52}}},
	}
	area = make([]int, 35)
	//查询MongoDB
	cursor, err := models.Mongo.Collection("actions").Aggregate(context.TODO(), mongo.Pipeline{match, group})
	if err != nil {
		return serializer.Response{
			Code:    500,
			Message: "服务器错误",
			Error:   err.Error(),
		}
	}
	// display the results
	var results []bson.M
	if err = cursor.All(context.TODO(), &results); err != nil {
		return serializer.Response{
			Code:    500,
			Message: "服务器错误",
			Error:   err.Error(),
		}
	}
	for _, result := range results {
		id := int(result["_id"].(int64))
		area[id] = int(result["count_total"].(int32))
	}
	return serializer.BuildAreaResponse(area)
}
